//package cn.lili.modules.kit.plugin.alipay;
//
//import cn.hutool.core.net.URLDecoder;
//import cn.hutool.core.net.URLEncoder;
//import cn.hutool.json.JSONUtil;
//import cn.lili.common.context.ThreadContextHolder;
//import cn.lili.common.enums.ResultCode;
//import cn.lili.common.exception.ServiceException;
//import cn.lili.common.properties.ApiProperties;
//import cn.lili.common.properties.DomainProperties;
//import cn.lili.common.utils.BeanUtil;
//import cn.lili.common.utils.ResultUtil;
//import cn.lili.common.utils.SnowFlake;
//import cn.lili.common.vo.ResultMessage;
//import cn.lili.modules.kit.Payment;
//import cn.lili.modules.payment.entity.dos.PaymentLog;
//import cn.lili.modules.payment.entity.dos.RefundLog;
//import cn.lili.modules.payment.entity.dos.UserWithdrawApply;
//import cn.lili.modules.payment.entity.dto.PayCallbackParam;
//import cn.lili.modules.payment.entity.dto.PayParam;
//import cn.lili.modules.payment.entity.dto.PaymentWakeupParam;
//import cn.lili.modules.payment.entity.enums.PaymentMethodEnum;
//import cn.lili.modules.payment.entity.enums.RefundStatusEnum;
//import cn.lili.modules.payment.service.PaymentService;
//import cn.lili.modules.payment.service.RefundLogService;
//import cn.lili.modules.system.client.SettingClient;
//import cn.lili.modules.system.entity.dos.Setting;
//import cn.lili.modules.system.entity.dto.payment.AlipayPaymentSetting;
//import cn.lili.modules.system.entity.enums.SettingEnum;
//import com.alibaba.fastjson.JSONObject;
//import com.alipay.api.AlipayApiException;
//import com.alipay.api.domain.*;
//import com.alipay.api.internal.util.AlipaySignature;
//import com.alipay.api.response.AlipayFundTransUniTransferResponse;
//import com.alipay.api.response.AlipayTradeQueryResponse;
//import com.alipay.api.response.AlipayTradeRefundResponse;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.nio.charset.StandardCharsets;
//import java.util.Map;
//
///**
// * 支付宝支付
// *
// * @author Chopper
// * @since 2020/12/17 09:55
// */
//@Slf4j
//@Component
//@RequiredArgsConstructor
//public class AliPayPlugin implements Payment {
//    /**
//     * 支付日志
//     */
//    private final PaymentService paymentService;
//    /**
//     * 退款日志
//     */
//    private final RefundLogService refundLogService;
//    /**
//     * 设置
//     */
//    private final SettingClient settingClient;
//    /**
//     * API域名
//     */
//    private final ApiProperties apiProperties;
//    /**
//     * 域名配置
//     */
//    private final DomainProperties domainProperties;
//
//    @Override
//    public ResultMessage<Object> h5pay(PaymentWakeupParam paymentWakeupParam) {
//
//        //准备支付参数
//        AlipayTradeWapPayModel payModel = new AlipayTradeWapPayModel();
//        //支付参数
//        PayParam payParam = paymentWakeupParam.getPayParam();
//        payModel.setBody(payParam.getTitle());
//        payModel.setSubject(payParam.getDetail());
//        payModel.setTotalAmount(String.valueOf(payParam.getPrice()));
//        //回传数据
//        payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(paymentWakeupParam.getPayParam()),
//                StandardCharsets.UTF_8));
//        //支付超时
//        payModel.setTimeoutExpress(paymentWakeupParam.getMinute());
//        payModel.setOutTradeNo(paymentWakeupParam.getOutTradeNo());
//        payModel.setProductCode("QUICK_WAP_PAY");
//        try {
//            log.info("支付宝H5支付：{}", JSONUtil.toJsonStr(payModel));
//            paymentWakeupParam.getPaymentLog().setPaymentRequestSource(JSONUtil.toJsonStr(payModel));
//            AliPayRequest.wapPay(ThreadContextHolder.getHttpResponse(), payModel, callbackUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY),
//                    notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY));
//        } catch (Exception e) {
//            log.error("H5支付异常", e);
//            throw new ServiceException(ResultCode.ALIPAY_EXCEPTION);
//        }
//        return null;
//    }
//
//
//    @Override
//    public ResultMessage<Object> jsApiPay(PaymentWakeupParam paymentWakeupParam) {
//        throw new ServiceException(ResultCode.PAY_NOT_SUPPORT);
//    }
//
//    @Override
//    public ResultMessage<Object> appPay(PaymentWakeupParam paymentWakeupParam) {
//        try {
//
//            AlipayTradeAppPayModel payModel = new AlipayTradeAppPayModel();
//
//            //支付参数
//            PayParam payParam = paymentWakeupParam.getPayParam();
//            payModel.setBody(payParam.getTitle());
//            payModel.setSubject(payParam.getDetail());
//            payModel.setTotalAmount(String.valueOf(payParam.getPrice()));
//
//            //支付超时
//            payModel.setTimeoutExpress(paymentWakeupParam.getMinute());
//            //回传数据
//            payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(paymentWakeupParam.getPayParam()),
//                    StandardCharsets.UTF_8));
//            payModel.setOutTradeNo(paymentWakeupParam.getOutTradeNo());
//            payModel.setProductCode("QUICK_MSECURITY_PAY");
//
//            log.info("支付宝APP支付：{}", payModel);
//
//
//            paymentWakeupParam.getPaymentLog().setPaymentRequestSource(JSONUtil.toJsonStr(payModel));
//
//            String orderInfo = AliPayRequest.appPayToResponse(payModel, notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY)).getBody();
//            log.info("支付宝APP支付返回内容：{}", orderInfo);
//            return ResultUtil.data(orderInfo);
//        } catch (AlipayApiException e) {
//            log.error("支付宝支付异常：", e);
//            throw new ServiceException(ResultCode.ALIPAY_EXCEPTION);
//        } catch (Exception e) {
//            log.error("支付业务异常：", e);
//            throw new ServiceException(ResultCode.PAY_ERROR);
//        }
//    }
//
//    @Override
//    public ResultMessage<Object> nativePay(PaymentWakeupParam paymentWakeupParam) {
//
//        try {
//            AlipayTradePrecreateModel payModel = new AlipayTradePrecreateModel();
//            //支付参数
//            PayParam payParam = paymentWakeupParam.getPayParam();
//            payModel.setBody(payParam.getTitle());
//            payModel.setSubject(payParam.getDetail());
//            payModel.setTotalAmount(String.valueOf(payParam.getPrice()));
//
//            //回传数据
//            payModel.setPassbackParams(URLEncoder.createAll().encode(BeanUtil.formatKeyValuePair(paymentWakeupParam.getPayParam()),
//                    StandardCharsets.UTF_8));
//            //支付超时
//            payModel.setTimeoutExpress(paymentWakeupParam.getMinute());
//            payModel.setOutTradeNo(paymentWakeupParam.getOutTradeNo());
//            log.info("支付宝扫码：{}", payModel);
//            String resultStr =
//                    AliPayRequest.tradePrecreatePayToResponse(payModel, notifyUrl(apiProperties.getBuyer(), PaymentMethodEnum.ALIPAY)).getBody();
//
//            log.info("支付宝扫码交互返回：{}", resultStr);
//
//
//            paymentWakeupParam.getPaymentLog().setPaymentRequestSource(JSONUtil.toJsonStr(payModel));
//
//            JSONObject jsonObject = JSONObject.parseObject(resultStr);
//            return ResultUtil.data(jsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code"));
//        } catch (Exception e) {
//            log.error("支付业务异常：", e);
//            throw new ServiceException(ResultCode.PAY_ERROR);
//        }
//    }
//
//    @Override
//    public void checkPaymentResult(PaymentLog paymentLog) {
//
//        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
//        model.setOutTradeNo(paymentLog.getOutTradeNo());
//        AlipayTradeQueryResponse alipayTradeQueryResponse = null;
//        try {
//            alipayTradeQueryResponse = AliPayApi.tradeQueryToResponse(model);
//        } catch (AlipayApiException e) {
//            throw new RuntimeException(e);
//        }
//
//
//        //标记已检查
//        paymentLog.setIsCheck(true);
//
//        //写入主动查询结果
//        paymentLog.setPaymentResponseSource(JSONUtil.toJsonStr(alipayTradeQueryResponse));
//        if (alipayTradeQueryResponse.isSuccess()) {
//            switch (alipayTradeQueryResponse.getTradeStatus()) {
//                //等待支付
//                case "WAIT_BUYER_PAY":
//                    //标记需要再次查询
//                    paymentLog.setIsCheck(false);
//                    paymentLog.setPaymentResponseSource("交易中，等待回传");
//                    return;
//                //已支付
//                case "TRADE_SUCCESS":
//                case "TRADE_FINISHED":
//                    String transactionId = alipayTradeQueryResponse.getTradeNo();
//                    paymentLog.setTransactionId(transactionId);
//                    paymentLog.setPrice(Double.valueOf(alipayTradeQueryResponse.getTotalAmount()));
//                    paymentLog.setIsPay(true);
//                    break;
//
//                //交易关闭
//                case "TRADE_CLOSED":
//                    return;
//            }
//        }
//    }
//
//    @Override
//    public void refund(RefundLog refundLog) {
//        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
//        model.setRefundAmount(String.valueOf(refundLog.getPrice()));
//        model.setRefundReason(refundLog.getRefundReason());
//        model.setOutRequestNo(refundLog.getOutRefundNo());
//        //交互退款
//        try {
//            AlipayTradeRefundResponse alipayTradeRefundResponse = AliPayApi.tradeRefundToResponse(model);
//            log.error("支付宝退款，参数：{},支付宝响应：{}", JSONUtil.toJsonStr(model), JSONUtil.toJsonStr(alipayTradeRefundResponse));
//            if (alipayTradeRefundResponse.isSuccess()) {
//                refundLog.setRefundStatus(RefundStatusEnum.REFUND.name());
//                refundLog.setOutRefundNo(alipayTradeRefundResponse.getTradeNo());
//            } else {
//                refundLog.setErrorMessage(String.format("错误码：%s,错误原因：%s", alipayTradeRefundResponse.getSubCode(),
//                        alipayTradeRefundResponse.getSubMsg()));
//            }
//            refundLogService.save(refundLog);
//        } catch (Exception e) {
//            log.error("支付退款异常：", e);
//            throw new ServiceException(ResultCode.PAY_ERROR);
//        }
//
//    }
//
//    @Override
//    public void refundNotify() {
//        //不需要实现
//    }
//
//    @Override
//    public void callBack() {
//        log.info("支付同步回调：");
//        callback();
//
//    }
//
//    @Override
//    public void paymentNotify() {
//        verifyNotify();
//        log.info("支付异步通知：");
//    }
//
//    /**
//     * 支付宝提现
//     * 文档地址：https://opendocs.alipay.com/open/02byuo?scene=ca56bca529e64125a2786703c6192d41&ref=api
//     *
//     * @param userWithdrawApply 会员提现申请
//     * @return
//     */
//    @Override
//    public boolean transfer(UserWithdrawApply userWithdrawApply) {
//        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
//        model.setOutBizNo(SnowFlake.createStr("T"));
//        model.setRemark("用户提现");
//        model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
//        model.setBizScene("DIRECT_TRANSFER");
//        Participant payeeInfo = new Participant();
//        payeeInfo.setIdentity(userWithdrawApply.getConnectNumber());
//        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
//        payeeInfo.setName(userWithdrawApply.getRealName());
//        model.setPayeeInfo(payeeInfo);
//
//        model.setTransAmount(userWithdrawApply.getApplyMoney().toString());
//        model.setProductCode("TRANS_ACCOUNT_NO_PWD");
//        model.setOrderTitle("用户提现");
//        //交互退款
//        try {
//            AlipayFundTransUniTransferResponse alipayFundTransUniTransferResponse = AliPayApi.uniTransferToResponse(model, null);
//            log.error("支付宝退款，参数：{},支付宝响应：{}", JSONUtil.toJsonStr(model), JSONUtil.toJsonStr(alipayFundTransUniTransferResponse));
//            if (alipayFundTransUniTransferResponse.isSuccess()) {
//
//            } else {
//                log.error(alipayFundTransUniTransferResponse.getSubMsg());
//            }
//        } catch (Exception e) {
//            log.error("用户提现异常：", e);
//            throw new ServiceException(ResultCode.PAY_ERROR);
//        }
//        return false;
//    }
//
//    /**
//     * 验证支付结果
//     */
//    private void callback() {
//        try {
//            AlipayPaymentSetting alipayPaymentSetting = alipayPaymentSetting();
//            //获取支付宝反馈信息
//            Map<String, String> map = AliPayApi.toMap(ThreadContextHolder.getHttpRequest());
//            log.info("同步回调：{}", JSONUtil.toJsonStr(map));
//            boolean verifyResult = AlipaySignature.rsaCertCheckV1(map, alipayPaymentSetting.getAlipayPublicCertPath(), "UTF-8", "RSA2");
//            if (verifyResult) {
//                log.info("支付回调通知：支付成功-参数：{}", map);
//            } else {
//                log.info("支付回调通知：支付失败-参数：{}", map);
//            }
//
//            ThreadContextHolder.getHttpResponse().sendRedirect(domainProperties.getWap() + "/pages/order/myOrder?status=0");
//        } catch (Exception e) {
//            log.error("支付回调同步通知异常", e);
//        }
//
//    }
//
//    /**
//     * 验证支付结果
//     */
//    private void verifyNotify() {
//        try {
//            AlipayPaymentSetting alipayPaymentSetting = alipayPaymentSetting();
//            //获取支付宝反馈信息
//            Map<String, String> map = AliPayApi.toMap(ThreadContextHolder.getHttpRequest());
//            log.info("支付回调响应：{}", JSONUtil.toJsonStr(map));
//            boolean verifyResult = AlipaySignature.rsaCertCheckV1(map, alipayPaymentSetting.getAlipayPublicCertPath(), "UTF-8", "RSA2");
//            //支付完成判定
//            if (!"TRADE_FINISHED".equals(map.get("trade_status")) && !"TRADE_SUCCESS".equals(map.get("trade_status"))) {
//                return;
//            }
//            String payParamStr = map.get("passback_params");
//            String payParamJson = URLDecoder.decode(payParamStr, StandardCharsets.UTF_8);
//            PayCallbackParam payCallbackParam = BeanUtil.formatKeyValuePair(payParamJson, new PayCallbackParam());
//
//
//            if (verifyResult) {
//                String tradeNo = map.get("trade_no");
//                Double totalAmount = Double.parseDouble(map.get("total_amount"));
//                PaymentSuccessParams paymentSuccessParams = new PaymentSuccessParams(PaymentMethodEnum.ALIPAY.name(), tradeNo, totalAmount,
//                        payCallbackParam, null, null);
//
//                paymentService.success(paymentSuccessParams);
//                log.info("支付回调通知：支付成功-参数：{},回调参数:{}", map, payCallbackParam);
//            } else {
//                log.info("支付回调通知：支付失败-参数：{}", map);
//            }
//        } catch (AlipayApiException e) {
//            log.error("支付回调通知异常", e);
//        }
//
//    }
//
//    /**
//     * 获取微信支付配置
//     *
//     * @return
//     */
//    private AlipayPaymentSetting alipayPaymentSetting() {
//        Setting setting = settingClient.get(SettingEnum.ALIPAY_PAYMENT.name());
//        if (setting != null) {
//            return JSONUtil.toBean(setting.getSettingValue(), AlipayPaymentSetting.class);
//        }
//        throw new ServiceException(ResultCode.ALIPAY_NOT_SETTING);
//    }
//
//}
